package cn.kgm.base.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 消息接收者
 */
public class Consumer {
    public static void main(String[] args) throws MQClientException {
        // 创建生产者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1" );
        // 设置nameserver地址
        consumer.setNamesrvAddr("192.168.101.9:9876" );
        // 指定订阅的topic和taag
        consumer.subscribe("kagim-topic-v1", "kagim-topic-v1-tag2-async" );
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                try {
                    if (!CollectionUtils.isEmpty(list)) {
                        for (MessageExt msg : list) {
                            System.out.println(new String(msg.getBody()));
                            System.out.println("消息消费掉了！===>" + msg.getBody());
                            // do somimg
                        }
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }
        });
        consumer.start();
        consumer.shutdown();
    }
}
